const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatTimeOnlyDate = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-');
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while(true) {
		now = new Date();
		if(now.getTime() > exitTime)
			return;
	}
}

function dateFormat(dateStr) {
	if(dateStr && dateStr != '') {
		return dateStr.substring(0, 4) + "/" + dateStr.substring(4, 6) +
			"/" + dateStr.substring(6, 8) + " " + dateStr.substring(8, 10) +
			":" + dateStr.substring(10, 12) + ":" + dateStr.substring(12, 14);
	}
	return "";
}

function dateFormatWithLeftSeporator(dateStr,leftSeporator) {
	if(dateStr && dateStr != '') {
		return dateStr.substring(0, 4) + leftSeporator + dateStr.substring(4, 6) +
			leftSeporator + dateStr.substring(6, 8) + " " + dateStr.substring(8, 10) +
			":" + dateStr.substring(10, 12) + ":" + dateStr.substring(12, 14);
	}
	return "";
}

function dateFormatOnlyDate(dateStr) {
	
	if(dateStr && dateStr != '') {
		dateStr = dateStr + ""
		return dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6) +
			"-" + dateStr.substring(6, 8);
	}
	return "";
}

function dateFormatOnlyDatAndMin(dateStr) {
	if(dateStr && dateStr != '') {
		dateStr = dateStr + ""
		return dateStr.substring(4, 6) +
			"/" + dateStr.substring(6, 8) + " " + dateStr.substring(8, 10) +
			":" + dateStr.substring(10, 12);
	}
	return "";
}

//格式化订单详情页面的时间格式
function formatOrderDetailTime(dateStr) {
	if(dateStr && dateStr != '') {
		dateStr = dateStr + ""
		return dateStr.substring(5, 16);
	}
	return "";
}

function isPoneAvailable(str) {
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
 	if(!myreg.test(str)) {
 		return false;
 	} else {
 		return true;
 	}
 }


module.exports = {
	formatTime: formatTime,
	formatTimeOnlyDate : formatTimeOnlyDate,
	sleep : sleep,
	dateFormat : dateFormat,
	dateFormatOnlyDate : dateFormatOnlyDate,
	isPoneAvailable : isPoneAvailable,
	dateFormatOnlyDatAndMin : dateFormatOnlyDatAndMin,
	dateFormatWithLeftSeporator : dateFormatWithLeftSeporator,
	formatOrderDetailTime : formatOrderDetailTime
}